package cn.hg.solon.youcan.system.provider;

import cn.hg.solon.youcan.common.enums.OnlineStatus;
import cn.hg.solon.youcan.easyquery.util.EntityQueryableUtil;
import cn.hg.solon.youcan.system.entity.EqUserOnline;
import cn.hg.solon.youcan.system.entity.UserOnline;
import cn.hg.solon.youcan.system.entity.proxy.EqUserOnlineProxy;
import cn.hg.solon.youcan.system.service.UserOnlineService;
import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.api.proxy.entity.select.EntityQueryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;
import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.db.Page;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 胡高
 */
@Component
public class EqUserOnlineProvider implements UserOnlineService {

    @Db("db1")
    private EasyEntityQuery easyEntityQuery;

    private EntityQueryable<EqUserOnlineProxy, EqUserOnline> buildQuery(Page page, Map<String, Object> map) {
        String word = (String) map.get("word");
        String status = (String) map.get("status");
        Date startDate = (Date) map.get("startDate");
        Date endDate = (Date) map.get("endDate");

        EntityQueryable<EqUserOnlineProxy, EqUserOnline> entityQueryable = this.easyEntityQuery
                // FROM sys_user_online AS t
                .queryable(EqUserOnline.class)
                // WHERE t.`status` = ${status} AND t.`start_datetime` > ${startDate} AND t.`start_datetime` < ${endDate}
                .where(t -> {
                    t.status().eq(StrValidator.isNotBlank(status), status);
                    t.startDatetime().rangeClosed(ObjUtil.isNotNull(startDate), startDate, ObjUtil.isNotNull(endDate), endDate);
                    // AND (t.`nickname` LIKE '%${word}%' OR t.`dept_name` LIKE '%${word}%' OR t.`ip` LIKE '%${word}%'
                    //      OR t.`location` LIKE '%${word}%' OR t.`browser` LIKE '%${word}%' OR t.`os` LIKE '%${word}%'
                    //      OR t.`id` LIKE '%${word}%')
                    t.or(StrValidator.isNotBlank(word), () -> {
                        t.nickname().like(word);
                        t.deptName().like(word);
                        t.ip().like(word);
                        t.location().like(word);
                        t.browser().like(word);
                        t.os().like(word);
                        t.id().like(word);
                    });
                });

        // ORDER BY ${sortField}
        return EntityQueryableUtil.applyOrderBy(entityQueryable, page);
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#get(java.lang.String)
     */
    @Override
    public EqUserOnline get(String token) {
        return this.easyEntityQuery.queryable(EqUserOnline.class).whereById(token).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#insert(cn.hg.solon.youcan.system.entity.UserOnline)
     */
    @Tran
    @Override
    public boolean insert(UserOnline bean) {
        EqUserOnline cloneBean = BeanUtil.copyProperties(bean, EqUserOnline.class);

        return this.easyEntityQuery.insertable(cloneBean).executeRows() > 0L;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#offline(java.lang.String)
     */
    @Tran
    @Override
    public boolean offline(String token) {
        return this.easyEntityQuery.updatable(EqUserOnline.class)
                .setColumns(t -> t.status().set(OnlineStatus.OFF.name()))
                .whereById(token)
                .executeRows() > 0L;

    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#onlineList()
     */
    @Override
    public List<EqUserOnline> onlineList() {
        return this.easyEntityQuery.queryable(EqUserOnline.class)
                .where(t -> t.status().eq(OnlineStatus.ON.name()))
                .toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<EqUserOnline> pageBy(Page page, Map<String, Object> paraMap) {
        EasyPageResult<EqUserOnline> pageList = this.buildQuery(page, paraMap).toPageResult(page.getPageNumber(), page.getPageSize());

        PageResult<EqUserOnline> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(Convert.toInt(pageList.getTotal()));

        return result;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#syncActivityTime(java.lang.String, java.util.Date)
     */
    @Tran
    @Override
    public void syncActivityTime(String token, Date datetime) {
        this.easyEntityQuery.updatable(EqUserOnline.class)
                .setColumns(t -> t.activityDatetime().set(datetime))
                .whereById(token)
                .executeRows();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserOnlineService#update(cn.hg.solon.youcan.system.entity.UserOnline)
     */
    @Tran
    @Override
    public boolean update(UserOnline bean) {
        EqUserOnline cloneBean = this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyEntityQuery.updatable(cloneBean).executeRows() > 0L;
    }

}
